//
//  LoginViewController.m
//  HondaPro_2
//
//  Created by glendale on 13-7-8.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "LoginViewController.h"
#import "AppDelegate.h"
#import "webConfig.h"
#import "webService.h"
#import "SVProgressHUD.h"
#import "NSData+Encryption.h"
#import "MyAFNetWorkManager.h"
#import "NetworkManager.h"
#import "SettingViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "HelpClass.h"
#import "DealerModle.h"
#import "ConfigCodeHelper.h"
#import "IQKeyboardManager.h"
#import "DealerView.h"

#define kAlertMessage(aMessage) dispatch_async(dispatch_get_main_queue(), ^{\
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:aMessage delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil, nil];\
[alert show];\
});

@interface LoginViewController ()

@property (weak, nonatomic) IBOutlet UIButton *siteBtn;
@property(nonatomic,strong)NSMutableArray *dealerArr;
@property(nonatomic,copy)NSString *ENTITY_CODE;
@property(nonatomic,copy)NSString *ENTITY_NAME;
@property(nonatomic,strong)DealerView *myview;

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _siteBtn.layer.borderWidth=1;
    _siteBtn.layer.borderColor=[UIColor colorWithWhite:(0xda / 255.0) alpha:1].CGColor;
    self.jingxiaoshangTextField.layer.borderWidth = 1;
       self.jingxiaoshangTextField.layer.borderColor=[UIColor colorWithWhite:(0xda / 255.0) alpha:1].CGColor;
      self.jingxiaoshangTextField.text =[[NSUserDefaults standardUserDefaults] objectForKey:@"jingxiaoshang"];
    self.usrTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    self.ENTITY_CODE = [[NSUserDefaults standardUserDefaults] objectForKey:@"ENTITY_CODE"];
    self.ENTITY_NAME = [[NSUserDefaults standardUserDefaults] objectForKey:@"ENTITY_NAME"];
    if (self.ENTITY_NAME) {
        [self.siteBtn setTitle:self.ENTITY_NAME forState:UIControlStateNormal];
    }

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (IBAction)siteBtnClicked {
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSData *dealerdata=[user objectForKey:@"dealerdata"];
    self.dealerArr = [NSKeyedUnarchiver unarchiveObjectWithData:dealerdata];
    if([self.dealerArr count]>0)
    {
        if(!_myview)
        {
            __weak typeof(self) weakSelf  = self;
            CGRect rectBtn=self.siteBtn.frame;
            CGRect viewframe=CGRectMake(rectBtn.origin.x, rectBtn.origin.y+rectBtn.size.height+2, rectBtn.size.width, 0);
            _myview=[[DealerView alloc]initWithFrame:viewframe andArr:self.dealerArr andSuperView:self.view];
            _myview.selectBlock=^(DealerModle *dealer)
            {
                [weakSelf.siteBtn setTitle:dealer.AscName forState:UIControlStateNormal];
                weakSelf.ENTITY_CODE=dealer.EntityCode;
                weakSelf.ENTITY_NAME=dealer.AscName;
                _myview=nil;
            };
        }
        else
        {
            [_myview removeFromSuperview];
            _myview =nil;
        }
    }
    else
    {
        kAlertMessage(@"经销商列表为空，请检查IP设置");
    }
}


- (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    //CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    CC_LONG    md5=(CC_LONG)strlen(cStr);
    CC_MD5(cStr,md5, result);
    NSString *lognstr=[NSString stringWithFormat:
                       @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                       result[0], result[1], result[2], result[3],
                       result[4], result[5], result[6], result[7],
                       result[8], result[9], result[10], result[11],
                       result[12], result[13], result[14], result[15]
                       ];
    
    return [lognstr substringToIndex:24];
}

- (IBAction)LogBtnSelect:(id)sender {
    
    [self.view endEditing:YES];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    
    NSLog(@"  经销商name   %@",[user objectForKey:@"name"]);
    NSLog(@"  经销商code    %@",[user objectForKey:@"code"]);
 
    
    NSArray * NameArr =[user objectForKey:@"name"];
    NSArray * codeArr =[user objectForKey:@"code"];
   
    self.jingxiaoshangTextField.text = [self.jingxiaoshangTextField.text uppercaseString];
    
 
    self.ENTITY_CODE = @"";
    for (NSString * nameStr in NameArr) {
        
        if ([nameStr isEqualToString:self.jingxiaoshangTextField.text]) {
            
//            NSLog(@"==========");
            NSInteger index = [NameArr indexOfObject:nameStr];
//            NSLog(@"==========%d",index);
            self.ENTITY_CODE = [codeArr objectAtIndex:index];
            break;
        }

        
    }
    
    NSLog(@"-------------%@",self.ENTITY_CODE);
    
    NSString *msg = [self validInput];
    if (msg) {
        kAlertMessage(msg);
        return;
    }
    [SVProgressHUD showWithStatus:@"登陆中...."];
    //将得到的用户名密码
    AppDelegate *myApp = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    myApp.userName = self.usrTextField.text;
    NSString *pwdStr = self.pwsTextField.text;
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:4];
    [dic setValue:self.ENTITY_CODE forKey:@"ENTITY_CODE"];
    [dic setValue:self.usrTextField.text forKey:@"USER_CODE"];
    [dic setValue:[self md5:pwdStr] forKey:@"PASSWORD"];
    [dic setValue:@"12781001" forKey:@"PAD_LOGIN"];
    
    [MyAFNetWorkManager postWithParam:dic andAction:@"LOGIN_ASC" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        if (error == nil)
        {
            [SVProgressHUD dismiss];
            NSDictionary *dic = obj;
            NSLog(@"登录接口： %@",obj);
            if([[dic valueForKey:@"SUCCESS"]integerValue]==1)
            {
                
                NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
                
                [user setObject:[dic valueForKey:@"USER_ID" ] forKey:@"userId"];
                [user setObject:[dic valueForKey:@"EMPLOYEE_NO" ] forKey:@"EMPLOYEE_NO"];
                [user setObject:self.ENTITY_CODE forKey:@"ENTITY_CODE"];
                [user setObject:self.ENTITY_NAME forKey:@"ENTITY_NAME"];
                [user setObject:self.usrTextField.text forKey:@"userName"];
                [user setObject:[self md5:self.pwsTextField.text] forKey:@"passWord"];
                [user setObject:[dic objectForKey:@"USER_NAME"] forKey:@"USER_NAME"];
                [user setObject:@"YES" forKey:@"IsLoginSuccess"];
                
                
                 [user setObject:self.jingxiaoshangTextField.text forKey:@"jingxiaoshang"];
                [user synchronize];
                
                
                [self getDataDictionary];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"QUERY_REPAIR_WORK_COUNT" object:nil];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
            else{
                kAlertMessage(obj[@"MSG"]);
            }
            
        }
        else{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        }
        
    }];
    
}

-(NSString *)validInput{
    NSString *msg = nil;
    if (!self.ENTITY_CODE) {
        msg = @"请输入正确的经销商代码！";
    }
    else if (self.usrTextField.text.length<=0){
        msg = @"请输入用户名";
    }else if (self.pwsTextField.text.length<=0){
        msg = @"请输入密码";
    }
    return msg;
}

-(void)loding:(NSNotification*)notification{
    
    [[ConfigCodeHelper shareInstance] updataPadDataSourceByKey:@"version"];
    
    self.loginBackData =(NSData*) notification.object;
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:self.loginBackData options:NSJSONReadingMutableLeaves error:Nil];
    [SVProgressHUD dismiss];
    NSLog(@"thejson=====%d",[[theJson objectForKey:@"error_code"] integerValue]);
    //用户名密码错误
    if ([[theJson objectForKey:@"error_code"] integerValue]==-1) {
        
        
        //弹出提示框
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                      message:[theJson objectForKey:@"error_msg"]
                                                     delegate:nil
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        [alert show];
    }else if ([[theJson objectForKey:@"error_code"] integerValue]==100){
        //弹出提示框
        UIAlertView*alert1 = [[UIAlertView alloc]initWithTitle:nil message:@"您的帐号已在其他Pad上登陆,您想要强制登陆吗！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"继续",nil];
        [alert1 setTag:1200];
        [alert1 show];
        [MainMenuDataModel sharedMainMenuDataModel].strCurrentSalerId = [theJson objectForKey:@"salerID"];
    }
    else{
        /*
         {"salerName":"1","salerID":"2001","tel":"","email":"","error_code":0,"error_msg":""}
         */
        
        //保存当前的操作人ID到数据模型中
        [MainMenuDataModel sharedMainMenuDataModel].strCurrentSalerId = [theJson objectForKey:@"salerID"];
        [MainMenuDataModel sharedMainMenuDataModel].dicSalerInfo = [NSDictionary dictionaryWithDictionary:theJson];
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
}

#pragma mark -
- (void)onTaskSuccess:(NSNotification*)notify {
    
    //提示更新版本！
    NetworkTask* task = notify.object;
    NSLog(@"%@",task.resultDict);
    NSString *serverVersionStr = [task.resultDict objectForKey:@"GHAC_AppVersion"];
    NSString *localVersionStr = [[HelpClass getDicDataFromConfigFileFromDocumnetFolder] objectForKey:@"GHAC_AppVersion"];
    if ([serverVersionStr doubleValue] > [localVersionStr doubleValue])
    {
        //更新系统
        AppDelegate *myApp = [[UIApplication sharedApplication] delegate];
        NSString *urlStr = [NSString stringWithFormat:@"itms-services://?action=download-manifest&url=http://%@/PadData/%@/HondaPro_2.plist",myApp.currentIp,APP_AND_SETUP_FILE_FOLDER_NAME_];
        //检测更新版本
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    [[NetworkingViewController sharedController] dismissNetworking];
}

- (void)onTaskFail:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    [[NetworkingViewController sharedController] dismissNetworking];
}

- (IBAction)IPSetAction:(id)sender {
    
    [self.view endEditing:YES];
//    AppDelegate *myApp = (AppDelegate*)[[UIApplication sharedApplication] delegate];
//    
//    NSString *title = [NSString stringWithFormat:@"您当前的IP地址是：\n%@",myApp.currentIp];
//    self.myAlertView=[[UIAlertView alloc] initWithTitle:title message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登入",nil];
//    
//    [self.myAlertView show];
    NSString* currentIP = [NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"ip"]];
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置IP"
                                                    message:[NSString stringWithFormat:@"当前IP:%@",currentIP]
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"完成", nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    alert.tag=500;
    UITextField* textField = [alert textFieldAtIndex:0];
    textField.delegate = self;

    textField.keyboardType = UIKeyboardTypeNumberPad;
    [alert show];
}



-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag==500) {
        //设置IP
        if (buttonIndex==1) {
            UITextField* textField = [alertView textFieldAtIndex:0];
            NSString *str = textField.text;
            if(textField.text.length>0)
            {
                [SVProgressHUD showWithStatus:@"加载中..."];
                [MyAFNetWorkManager getWithAction:@"QUERY_ALL_ASC_INFO" andipstr:str finish:^(NSData *data, NSDictionary *obj, NSError *error) {
                    [SVProgressHUD dismiss];
                    
                    
                    NSLog(@"设置IP：%@",obj);
                    if (error == nil)
                    {
                        if([[obj valueForKey:@"SUCCESS"]intValue]==1)
                        {
                            NSMutableArray *dealerArr=[NSMutableArray array];
                            
                            NSMutableArray *Lname = [[NSMutableArray alloc]init];
                            
                            NSMutableArray *Lcode = [[NSMutableArray alloc]init];
                            
                            id dataArr=[obj objectForKey:@"TM_ASC_BASICINFO"];
                            
                            
                            if([dataArr isKindOfClass:[NSArray class]])
                            {
                                for (NSDictionary *dic in dataArr) {
                                    DealerModle *dealer=[[DealerModle alloc]init];
                                    dealer.DealerCode=[dic objectForKey:@"DealerCode"];
                                    dealer.AscName=[dic objectForKey:@"AscName"];
                                    dealer.AscShortname=[dic objectForKey:@"AscShortname"];
                                    dealer.EntityCode=[dic objectForKey:@"EntityCode"];
                                    
                                    [dealerArr addObject:dealer];
                                    [Lname addObject:[dic objectForKey:@"DealerCode"]];
                                    [Lcode addObject:[dic objectForKey:@"EntityCode"]];
                                }
                                
                                if([dealerArr count]>0)
                                {
                                    //DealerModle *dealer=[dealerArr objectAtIndex:0];
                                    //                                    [_login.siteBtn setTitle:dealer.AscName forState:UIControlStateNormal];
                                    //                                    _login.ENTITY_CODE=dealer.EntityCode;
                                    
                                }
                                
                                NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
                                NSData *dealerdata = [NSKeyedArchiver archivedDataWithRootObject:dealerArr];
                                [user setObject:dealerdata forKey:@"dealerdata"];
                                
                                
                                [user setObject:Lname forKey:@"name"];
                                [user setObject:Lcode forKey:@"code"];
                                
                                [user setObject:str forKey:@"ip"];
                                [user synchronize];
                            }
                        }
                    }
                    else
                    {
                        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                    }
                }];
            }
            else{
                [SVProgressHUD showErrorWithStatus:@"IP不能为空"];
            }
        }
    }
    else if (alertView.tag==1200){
        if (buttonIndex==1) {
           
            [SVProgressHUD showWithStatus:@"登陆中...." maskType:SVProgressHUDMaskTypeGradient];
            //将得到的用户名密码
            AppDelegate *myApp = (AppDelegate*)[[UIApplication sharedApplication] delegate];
            myApp.userName = self.usrTextField.text;
            NSString *pwdStr = self.pwsTextField.text;
            
            //加密
            
            NSString *key = @"Honda20130000000";
            
            NSData *plain = [pwdStr dataUsingEncoding:NSUTF8StringEncoding];
            
            NSData *cipher = [plain AES256EncryptWithKey:key];
            
            NSString *pwdKey= [NSData base64Encode:cipher];
            
            NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *realPath = [documentPath stringByAppendingPathComponent:@"Config.plist"];
            
            
            
            //ping url
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:realPath]) {
                
                NSString *mid = [[NSDictionary dictionaryWithContentsOfFile:realPath] objectForKey:@"mid"];
                
                
                NSMutableArray *paras=[NSMutableArray arrayWithObjects:@"usr",self.usrTextField.text,@"psw",pwdKey,@"mid",mid,@"flag",@"1", nil];
                
                //发送服务器请求
                webService *web=[[webService alloc] init];
                web.methodName = LOGIN;
                [web commonGetSharedRequest:LOGIN wsparas:paras];
            }
            
            
        }
    }

}
- (void)onTaskSuccessabcs:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    NSLog(@"%@",task.resultDict);
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    if([task.indentifier isEqualToString:@"SettingIP"])
    {
      if (200 == task.statusCode) {//成功设置IP
        
        [[NetworkingViewController sharedController] showNetworkingWithTitle:@"设置成功!" content:nil activiting:NO enableDismiss:YES];
          NSLog(@"%@",self.currentIp);
        
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *realPath = [documentPath stringByAppendingPathComponent:@"Config.plist"];
        
        NSMutableDictionary *dictplist = [NSDictionary dictionaryWithContentsOfFile:realPath];
        
        //设置属性值
        [dictplist setObject:self.currentIp forKey:@"ip"];
        
        //写入文件
        [dictplist writeToFile:realPath atomically:YES];
        
        [[NSUserDefaults standardUserDefaults] setObject:self.currentIp forKey:@"ip"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [NetworkManager getInstance].host = self.currentIp;
        
        [SettingViewController shareInstance];//设置界面中创建需要更新车辆的消息相应事件
        [ConfigCodeHelper shareInstance];//初始化缓存中的数据，以及发送需要更新的车辆消息
        
        
        [[NetworkingViewController sharedController] performSelector:@selector(dismissNetworking) withObject:nil afterDelay:1.5];
        
    } else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置IP" message:@"设置失败，请重新设置!" delegate:self cancelButtonTitle:@"完成" otherButtonTitles:nil, nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        UITextField* textField = [alert textFieldAtIndex:0];
        textField.delegate = self;
        textField.keyboardType = UIKeyboardTypeNumberPad;
        [alert show];
        //        SafeRelease(alert);
        [[NetworkingViewController sharedController] dismissNetworking];
    }
    }
}

- (void)onTaskFailabcs:(NSNotification*)notify {
    NSLog(@"cccc");
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    if([task.indentifier isEqualToString:@"SettingIP"])
    {
      UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置IP" message:@"设置失败，请检查网络!" delegate:self cancelButtonTitle:@"完成" otherButtonTitles:nil, nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField* textField = [alert textFieldAtIndex:0];
    textField.delegate = self;
    textField.keyboardType = UIKeyboardTypeNumberPad;
    [alert show];
    [[NetworkingViewController sharedController] dismissNetworking];
    }
}

//#pragma mark -
//- (void)onTaskSuccess:(NSNotification*)notify {
//    NetworkTask* task = notify.object;
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
//    
//    if (200 == task.statusCode) {//成功设置IP
//        AppDelegate *myApp = (AppDelegate*)[[UIApplication sharedApplication] delegate];
//        
//        [[NSUserDefaults standardUserDefaults] setObject:myApp.currentIp forKey:@"ip"];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//        
//        
//        [NetworkManager getInstance].host = myApp.currentIp;
//        
//        [SettingViewController shareInstance];//设置界面中创建需要更新车辆的消息相应事件
//        [ConfigCodeHelper shareInstance];//初始化缓存中的数据，以及发送需要更新的车辆消息
//        
//        [[NetworkingViewController sharedController] showNetworkingWithTitle:@"设置成功!" content:nil activiting:NO enableDismiss:NO];
//        [[NetworkingViewController sharedController] performSelector:@selector(dismissNetworking) withObject:nil afterDelay:1.5];
//        
//        
//    } else {
//
//       
//        [[NetworkingViewController sharedController] dismissNetworking];
//    }
//    //    SafeRelease(_ipConfig);
//}
//
//- (void)onTaskFail:(NSNotification*)notify {
//  
//    //    SafeRelease(alert);
//    [[NetworkingViewController sharedController] dismissNetworking];
//    //    SafeRelease(_ipConfig);
//}



- (void)viewDidUnload {
    [self setUsrTextField:nil];
    [self setPwsTextField:nil];
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:LOGIN object:Nil];
    [super viewDidUnload];
}

//获取数据字典
-(void)getDataDictionary
{
    //QUERY_DIC_FOR_SALES_PAD
    NSString   *actionLogin=[NSString stringWithFormat:@"QUERY_DIC_FOR_SALES_PAD"];
    
    //_WEAK_SELF
    [[NetworkingViewController sharedController] showNetworkingWithTitle:nil content:@"查询中，请稍后..." activiting:YES enableDismiss:NO];
    
    [MyAFNetWorkManager postWithParam:nil andAction:actionLogin finish:^(NSData *data, NSDictionary *obj, NSError *error)
     {
         [[NetworkingViewController sharedController] dismissNetworking];
         if (error == nil)
         {
             NSDictionary  *returnDic=(NSDictionary *)obj;
             NSLog(@"全部数据字典：%@",returnDic);
             [[NetworkingViewController sharedController] showNetworkingWithTitle:@"数据更新成功！" content:nil activiting:NO enableDismiss:NO];
             [[NetworkingViewController sharedController] performSelector:@selector(dismissNetworking) withObject:nil afterDelay:1.5];
             NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
             NSString *paths=[[path objectAtIndex:0] stringByAppendingPathComponent:@"Dic.text"];
             [returnDic writeToFile:paths atomically:YES];
         }
         else
         {
             NSLog(@"%@",error);
         }
     }];
}

@end
